/**
 * Created by leiweibo on 7/11/15.
 */


var app = angular.module('marketcontroller', []);
var count = 0;


app.filter('offset', function () {
  return function (input, start) {
    start = parseInt(start, 10);
    return input.slice(start);
  };
});

app.controller('MarketCtrl', function ($scope, HosptialAggregateService, MarketService, $routeParams) {

  $scope.hospitalId = $routeParams.param;

  var action = $routeParams.action;
  if (action) {
    var options = {
      'expiration': Math.floor(new Date().getTime() / 1000) + 86400,
      bucket: 'vistrack-attach-prd',
      'save-key': '/{filemd5}{.suffix}'
    };
    // 查看更多参数：http://docs.upyun.com/api/form_api/#表单API接口简介
    var policy = window.btoa(JSON.stringify(options));
    // 从 UPYUN 用户管理后台获取表单 API
    var form_api_secret = '5ri+TpAfi0lw+O9eaH9PBMYoSHI=';
    // 计算签名
    var signature = md5(policy + '&' + form_api_secret);
    var url_prefix = "http://" + options.bucket + ".b0.upaiyun.com";
    var uploader = new plupload.Uploader({
      runtimes: 'html5,flash,silverlight,html4',
      browse_button: 'browser_version_desc', // you can pass in id...
      container: document.getElementById('container_version_desc'),
      flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
      silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap',
      multi_selection:false,
      url: 'http://v0.api.upyun.com/' + options.bucket,

      multipart_params: {
        'Filename': '${filename}', // adding this to keep consistency across the runtimes
        'Content-Type': '',
        'policy': policy,
        'signature': signature
      },

      init: {
        PostInit: function () {
          //do nothing here.
        },

        FilesAdded: function (up, files) {
          plupload.each(files, function (file) {
            uploader.start();
          });
        },

        UploadProgress: function (up, file) {
          $('#percentage').text(file.percent + "%");
        },

        FileUploaded: function (up, file, info) {
          var response = JSON.parse(info.response);
          $scope.version_desc_url = url_prefix + response.url;
        },

        Error: function (up, err) {
          $("#percentage").text("上传失败");
        }
      }
    });
    uploader.init();
  }


  HosptialAggregateService.list_hospital_group_by_province(true, function(res, data) {

    if (res.result == true) {
      $scope.hospitalsData = res.hospitals;
    } else {
      $scope.error_msg = res.message;
    }
  });

  $scope.callServer = function (tableState) {

    $scope.isLoading = true;

    var pagination = tableState.pagination;
    var pageSize = pagination.number || 20;
    var pageNo = Math.ceil((pagination.start + 1) / pageSize) || 1;

    HosptialAggregateService.list_market_by_hospital($scope.hospitalId, function(res) {
      $scope.hospital = res.hospital;
      $scope.displayed = res.records;
      tableState.pagination.numberOfPages = res.pageCount;
      $scope.isLoading = false;
      $scope.noRecord = (res.recordCount <= 0);
      $scope.completed = res.hospital.type == 1;
    });
  };

  $scope.add = function() {
    window.location = "#/create_market_record/" + $scope.hospitalId + "/add";
  };

  $scope.cancel = function() {
    window.location = "#/market_list/" + $scope.hospitalId;
  }

  $scope.createOrUpdate = function() {

    if ($('#percentage').text() && $('#percentage').text() != '100%') {
      alert("文件上传未完成，请稍后");
      return;
    }

    var version_desc_attach = new Attachment($scope.version_desc, $scope.version_desc_url);
    var formData = {
      step: $scope.step,
      name: $scope.name,
      hospital: $scope.hospitalId,
      version_desc: version_desc_attach,
      hospital_officer: $scope.hospital_officer,
      hospital_phone: $scope.hospital_phone,
      desc: $scope.desc,
      finished: $scope.finished
    };

    MarketService.create(formData, function(res) {
      if (res.result == true) {
        delete $scope.name,
        delete $scope.step,
        delete $scope.hospital_phone,
        delete $scope.hospital_officer,
        delete $scope.desc,
        delete $scope.finished,
        delete $scope.version_desc,
        delete $scope.version_desc_url;
        alert('添加市场开发步骤成功');
      } else {
        $scope.error_msg = res.message;
      }
    }, function(data, status) {
      $scope.error_msg = '无权限进行此操作';
    })
  }

});

var Attachment = function(desc, url) {
  this.url = url;
  this.desc = desc;
}
